import request from '@/utils/request'
import type { ApiResponse, PageResponse } from '@/types/api'

// 文件信息类型定义
export interface FileInfoVO {
  id: string
  displayName: string
  originalName: string
  mimeType: string
  fileSize: number
  humanReadableSize: string
  businessType: string
  storageObjectId: string
  storageProvider: string
  storageKey: string
  description?: string
  uploaderName: string
  uploaderId: string
  uploadTime: string
  isPublic: boolean
  status: number
  downloadCount: number
  lastDownloadTime?: string
  tenantId: string
  createTime: string
  updateTime: string
}

// 文件查询参数
export interface FileQueryParams {
  current?: number
  size?: number
  keyword?: string
  businessType?: string
  uploaderId?: string
  status?: number
  mimeType?: string
  startTime?: string
  endTime?: string
}

// 文件上传响应
export interface FileUploadResponse {
  fileId: string
  displayName: string
  originalName: string
  fileSize: number
  mimeType: string
  downloadUrl: string
}

// 文件管理API
export const fileApi = {
  // 获取文件列表（分页）
  getFileList: (params: FileQueryParams): Promise<ApiResponse<PageResponse<FileInfoVO>>> => {
    return request.get('/file/fileinfo/list', { params })
  },

  // 获取文件详情
  getFileInfo: (fileId: string): Promise<ApiResponse<FileInfoVO>> => {
    return request.get(`/file/fileinfo/${fileId}`)
  },

  // 上传文件
  uploadFile: (
    file: File, 
    businessType = 'general', 
    description?: string, 
    onProgress?: (progressEvent: ProgressEvent) => void
  ): Promise<ApiResponse<FileUploadResponse>> => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('businessType', businessType)
    if (description) {
      formData.append('description', description)
    }
    
    return request.post('/file/fileinfo/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: onProgress
    })
  },

  // 批量上传文件
  uploadMultipleFiles: (files: File[], businessType = 'general'): Promise<ApiResponse<FileUploadResponse[]>> => {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    formData.append('businessType', businessType)
    
    return request.post('/file/fileinfo/upload/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取下载链接
  getDownloadUrl: (fileId: string, expireMinutes = 60): Promise<ApiResponse<string>> => {
    return request.get(`/file/fileinfo/download-url/${fileId}`, {
      params: { expireMinutes }
    })
  },

  // 下载文件
  downloadFile: (fileId: string): Promise<void> => {
    return request.get(`/file/fileinfo/download/${fileId}`, {
      responseType: 'blob'
    }).then((response: any) => {
      const blob = new Blob([response])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'file'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  },

  // 重命名文件
  renameFile: (fileId: string, newDisplayName: string): Promise<ApiResponse<boolean>> => {
    return request.put(`/file/fileinfo/${fileId}/rename`, null, {
      params: { newDisplayName }
    })
  },

  // 更新文件描述
  updateFileDescription: (fileId: string, description: string): Promise<ApiResponse<boolean>> => {
    return request.put(`/file/fileinfo/${fileId}/description`, null, {
      params: { description }
    })
  },

  // 删除文件
  deleteFile: (fileId: string): Promise<ApiResponse<boolean>> => {
    return request.delete(`/file/fileinfo/${fileId}`)
  },

  // 批量删除文件
  deleteMultipleFiles: (fileIds: string[]): Promise<ApiResponse<{
    successCount: number
    failureCount: number
    failures: Array<{ fileId: string; reason: string }>
  }>> => {
    return request.delete('/file/fileinfo/batch', { data: fileIds })
  },

  // 复制文件
  copyFile: (fileId: string, newDisplayName?: string): Promise<ApiResponse<FileUploadResponse>> => {
    return request.post(`/file/fileinfo/${fileId}/copy`, {
      newDisplayName
    })
  },

  // 获取文件统计信息
  getFileStatistics: (): Promise<ApiResponse<{
    totalFiles: number
    totalSize: number
    totalSizeHumanReadable: string
    filesByType: Array<{ mimeType: string; count: number; size: number }>
    filesByBusinessType: Array<{ businessType: string; count: number; size: number }>
    recentUploads: number
    popularFiles: Array<{ fileId: string; displayName: string; downloadCount: number }>
  }>> => {
    return request.get('/file/fileinfo/statistics')
  }
}

// 文件存储配置API (已废弃，请使用 FileStorageConfig)
export interface StorageConfigDTO {
  defaultProvider: string
  defaultBucket: string
  local: {
    rootPath: string
    createDateSubDir: boolean
  }
  share: {
    baseUrl: string
    pathPrefix: string
  }
}

// 新的多配置存储配置
export interface FileStorageConfig {
  id?: string
  configName: string
  configType: string
  description?: string
  configParams: string
  isEnabled: boolean
  isDefault: boolean
  sortOrder: number
  tenantId?: string
  createTime?: string
  updateTime?: string
}

// 分页查询参数
export interface StorageConfigQueryParams {
  current?: number
  size?: number
  configName?: string
  configType?: string
  enabled?: boolean
}

// 存储类型选项
export interface StorageTypeOption {
  value: string
  label: string
  description: string
}

// 旧的文件配置API已移除，请使用 fileStorageConfigApi

// 新的存储配置管理API
export const fileStorageConfigApi = {
  // 分页查询存储配置
  getStorageConfigs: (params: StorageConfigQueryParams): Promise<ApiResponse<PageResponse<FileStorageConfig>>> => {
    return request.get('/file/storage-config/page', { params })
  },

  // 获取所有启用的配置
  getEnabledConfigs: (): Promise<ApiResponse<FileStorageConfig[]>> => {
    return request.get('/file/storage-config/enabled')
  },

  // 根据类型获取配置
  getConfigsByType: (configType: string): Promise<ApiResponse<FileStorageConfig[]>> => {
    return request.get(`/file/storage-config/type/${configType}`)
  },

  // 获取默认配置
  getDefaultConfig: (): Promise<ApiResponse<FileStorageConfig>> => {
    return request.get('/file/storage-config/default')
  },

  // 根据ID获取配置详情
  getConfig: (configId: string): Promise<ApiResponse<FileStorageConfig>> => {
    return request.get(`/file/storage-config/${configId}`)
  },

  // 创建存储配置
  createConfig: (config: FileStorageConfig): Promise<ApiResponse<FileStorageConfig>> => {
    return request.post('/file/storage-config', config)
  },

  // 更新存储配置
  updateConfig: (configId: string, config: FileStorageConfig): Promise<ApiResponse<FileStorageConfig>> => {
    return request.put(`/file/storage-config/${configId}`, config)
  },

  // 删除存储配置
  deleteConfig: (configId: string): Promise<ApiResponse<void>> => {
    return request.delete(`/file/storage-config/${configId}`)
  },

  // 批量删除
  batchDeleteConfigs: (configIds: string[]): Promise<ApiResponse<{ deletedCount: number }>> => {
    return request.delete('/file/storage-config/batch', { data: configIds })
  },

  // 设置默认配置
  setDefaultConfig: (configId: string): Promise<ApiResponse<void>> => {
    return request.put(`/file/storage-config/${configId}/default`)
  },

  // 切换配置状态
  toggleConfigStatus: (configId: string, enabled: boolean): Promise<ApiResponse<void>> => {
    return request.put(`/file/storage-config/${configId}/toggle`, null, { params: { enabled } })
  },

  // 更新排序
  updateSortOrder: (configs: Pick<FileStorageConfig, 'id' | 'sortOrder'>[]): Promise<ApiResponse<void>> => {
    return request.put('/file/storage-config/sort', configs)
  },

  // 测试连接
  testConnection: (config: FileStorageConfig): Promise<ApiResponse<{ success: boolean; message: string }>> => {
    return request.post('/file/storage-config/test', config)
  },

  // 验证配置参数
  validateConfig: (configType: string, configParams: string): Promise<ApiResponse<{ valid: boolean; message: string }>> => {
    return request.post('/file/storage-config/validate', null, { 
      params: { configType, configParams } 
    })
  },

  // 复制配置
  copyConfig: (configId: string, newConfigName: string): Promise<ApiResponse<FileStorageConfig>> => {
    return request.post(`/file/storage-config/${configId}/copy`, null, { 
      params: { newConfigName } 
    })
  },

  // 获取存储类型选项
  getStorageTypeOptions: (): Promise<ApiResponse<StorageTypeOption[]>> => {
    return request.get('/file/storage-config/storage-types')
  },

  // 获取配置参数模板
  getConfigTemplate: (configType: string): Promise<ApiResponse<Record<string, any>>> => {
    return request.get(`/file/storage-config/template/${configType}`)
  },

  // 获取使用统计
  getUsageStats: (): Promise<ApiResponse<Array<Record<string, any>>>> => {
    return request.get('/file/storage-config/stats')
  },

  // 导出配置
  exportConfigs: (configIds: string[]): Promise<ApiResponse<Array<Record<string, any>>>> => {
    return request.post('/file/storage-config/export', configIds)
  },

  // 导入配置
  importConfigs: (configData: Array<Record<string, any>>): Promise<ApiResponse<{ successCount: number; errorCount: number; errors: string[] }>> => {
    return request.post('/file/storage-config/import', configData)
  },

  // 检查名称唯一性
  checkConfigName: (configName: string, excludeId?: string): Promise<ApiResponse<{ unique: boolean }>> => {
    const params: any = { configName }
    if (excludeId) params.excludeId = excludeId
    return request.get('/file/storage-config/check-name', { params })
  },

  // 手动重新加载配置（配置热更新）
  reloadConfiguration: (): Promise<ApiResponse<Record<string, any>>> => {
    return request.post('/file/storage-config/reload')
  },

  // 获取当前生效的配置信息
  getCurrentConfig: (): Promise<ApiResponse<Record<string, any>>> => {
    return request.get('/file/storage-config/current')
  }
}

export default fileApi
